from django.contrib.auth.models import User, Group
from django.db import models
import json
import os
import uuid
# Create your models here.

class Chart(models.Model):
    title = models.CharField(max_length=255)
    is_activte = models.BooleanField(default=True)
    # 存储json数据
    parameters = models.TextField(default='{}',null=True)
    created = models.DateTimeField(auto_now_add=True)

    def to_json(self):
        return {
            "id": self.id,
            "title": self.title,
            'parameters': json.loads(self.parameters)
        }

    class Meta:
        ordering = ('created',)


class DataItem(models.Model):
    name = models.CharField(max_length=255)
    value = models.IntegerField()
    item_date = models.DateTimeField()
    chart = models.ForeignKey(Chart,on_delete=models.CASCADE,)

    def to_json(self):
        return {
            "id": self.id,
            "name": self.name,
            'value': self.value,
            'date': self.item_date.strftime('%Y/%m/%d')
        }

class ItemClass(models.Model):
    name = models.CharField(max_length=255)
    color = models.CharField(max_length=255)


class FwNewsPowerClass(models.Model):
    POWER_CHOICES = (
        ('1', 'read'),
        ('2', 'change'),
        ('3', 'delete'),
    )
    power = models.CharField(
        max_length=1,
        choices=POWER_CHOICES,
        default='1',
    )
    name = models.CharField(max_length=128)
    user = models.ForeignKey(User, on_delete=models.CASCADE,)
    created = models.DateTimeField(auto_now_add=True)

    def to_json(self):
        return {
            "id": self.id,
            "name": self.name,
            'power': self.power,
            'user': self.user.username,
            'date': self.created.strftime('%Y/%m/%d')
        }

def user_directory_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = '{}.{}'.format(uuid.uuid4().hex[:8], ext)
    sub_folder = 'file'
    if ext.lower() in ["jpg", "png", "gif"]:
        sub_folder = "img"
    if ext.lower() in ["pdf", "docx", "xlsx"]:
        sub_folder = "document"
    return os.path.join(instance.user.id, sub_folder, filename)

class AiImgModel(models.Model):
    project =  models.CharField(max_length=128)
    photo = models.ImageField(upload_to="ai_img",null=True, blank=True)
    predict = models.CharField(max_length=64, null=True, blank=True)
    is_correct = models.BooleanField(default=True)
    fix_name = models.CharField(max_length=64, null=True, blank=True)